package com.hippoDocker.security.pojo.dto;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName LoginUserDTO
 * @Description TODO 登录用户信息
 * @Author tangxl
 * @Date 2022/7/26 11:00
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
//使用@JsonIgnoreProperties注解，可以在User对象在序列化时忽略这些字段
@JsonIgnoreProperties(ignoreUnknown=true)
public class LoginUserDTO implements UserDetails {
    /**
     * 系统用户信息
     */
    private UmsMemberDTO umsMember;

    /**
     * 用户权限
     */
    private List<String> permissions;

    /**
     * 权限信息列表
     */
    @JSONField(serialize = false)//GrantedAuthority为spring里面的类不进行序列化到redis中
    private List<GrantedAuthority> getAuthoritys;

    public LoginUserDTO(UmsMemberDTO umsMember, List<String> permission) {
        this.umsMember = umsMember;
        this.permissions = permission;
    }

    /**
     * 获取权限信息
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //判断是否权限列表是否已经有权限
        if(!CollectionUtils.isEmpty(getAuthoritys)){
            return getAuthoritys;
        }
        //将permission中的String类型权限信息封装成SimpleGrantedAuthority对象
        //方法一：for循环实现
//        List<GrantedAuthority> getAuthoritys = new ArrayList<>();
//        for (String permission:permissions){
//            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission);
//            getAuthoritys.add(simpleGrantedAuthority);
//        }
        //方法二：stream流实现
        getAuthoritys = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return getAuthoritys;
    }

    /**
     * 获取密码
     * @return
     */
    @Override
    public String getPassword() {
        return umsMember.getPassword();
    }

    /**
     * 获取用户名
     * @return
     */
    @Override
    public String getUsername() {
        return umsMember.getUsername();
    }

    /**
     * 判断是否没有过期
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 是否没有锁定
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 是否没有超时
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否可用
     * @return
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
